package com.etonedu.meals.utils;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.Toast;

import com.etonedu.meals.R;
import com.etonedu.meals.dialog.HttpUrlDialog;
import com.etonedu.meals.dialog.InternetDialog;
import com.etonedu.meals.dialog.WindowDialog;
import com.etonedu.meals.enumeration.MessageEnum;
import com.etonedu.meals.machine.DeviceUtils;

import org.greenrobot.eventbus.EventBus;
import org.xutils.x;

/**
 * Created by Administrator on 2016/4/8.
 */
public class WindowUtils {
    private static final String LOG_TAG = "WindowUtils";
    private static View mView;
    private static WindowManager mWindowManager;
    private static Context mContext;
    private static Activity mActivity;

    private InternetDialog.Builder builder;

    public static Boolean isShown = false;

    public static void showPopupWindow(final Activity context) {
        isShown = true;

        mActivity = context;
        mContext = context.getApplicationContext();
        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);

        // 获取屏幕宽高（方法1）
        int screenWidth = mWindowManager.getDefaultDisplay().getWidth(); // 屏幕宽（像素，如：480px）
        int screenHeight = mWindowManager.getDefaultDisplay().getHeight();

        mView = setUpView(context);
        final WindowManager.LayoutParams params = new WindowManager.LayoutParams();

        params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        params.flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
        params.format = PixelFormat.TRANSLUCENT;

        params.width = screenWidth - screenWidth/3;
        params.height = screenHeight - (int)(screenHeight/2.5);

        params.gravity = Gravity.CENTER;

        mWindowManager.addView(mView, params);
    }

    /**
     * 隐藏弹出框
     */
    public static void hidePopupWindow() {
        if (isShown && null != mView) {
            mWindowManager.removeView(mView);
            isShown = false;
        }

    }

    private static View setUpView(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_keyboard,null);
        Button btn_one = (Button) view.findViewById(R.id.btn_one);
        Button btn_two = (Button) view.findViewById(R.id.btn_two);
        Button btn_three = (Button) view.findViewById(R.id.btn_three);

        Button btn_four = (Button) view.findViewById(R.id.btn_four);
        Button btn_five = (Button) view.findViewById(R.id.btn_five);
        Button btn_six = (Button) view.findViewById(R.id.btn_six);

        Button btn_seven = (Button) view.findViewById(R.id.btn_seven);
        Button btn_eight = (Button) view.findViewById(R.id.btn_eight);
        Button btn_nine = (Button) view.findViewById(R.id.btn_nine);

        Button btn_temp = (Button) view.findViewById(R.id.btn_windows_temp);
        Button btn_zero = (Button) view.findViewById(R.id.btn_zero);
        Button btn_go_back = (Button) view.findViewById(R.id.btn_go_back);

        btn_one.setOnClickListener(new KeyBoardOnClickListener());
        btn_two.setOnClickListener(new KeyBoardOnClickListener());
        btn_three.setOnClickListener(new KeyBoardOnClickListener());

        btn_four.setOnClickListener(new KeyBoardOnClickListener());
        btn_five.setOnClickListener(new KeyBoardOnClickListener());
        btn_six.setOnClickListener(new KeyBoardOnClickListener());

        btn_seven.setOnClickListener(new KeyBoardOnClickListener());
        btn_eight.setOnClickListener(new KeyBoardOnClickListener());
        btn_nine.setOnClickListener(new KeyBoardOnClickListener());

        btn_zero.setOnClickListener(new KeyBoardOnClickListener());
        btn_go_back.setOnClickListener(new KeyBoardOnClickListener());

        String result = Utils.do_exec("wm size");
        result = result.replace("Physical size","分辨率");
        btn_temp.setTextSize(20);
        btn_temp.setTextColor(Color.WHITE);
        btn_temp.setText(result);

        return view;
    }

    private static class KeyBoardOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {

            int id = v.getId();
            boolean isAppInstall = Utils.isAppInstalled(x.app(),"com.etonedu.autoboot");

                if(id == R.id.btn_one) {
//                    showToast("1");
//                    showInternetDialog(mActivity);

                    HttpUrlDialog dialog = new HttpUrlDialog(mActivity,R.style.CustomDialog);
                    dialog.show();

                    hidePopupWindow();
                } else if (id == R.id.btn_two) {
//                    showToast("2");
                    Intent intent = new Intent(Settings.ACTION_SETTINGS);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(intent);
                    hidePopupWindow();
                } else if (id == R.id.btn_three) {
//                    showToast("3");
//                    Intent intent1 =  new Intent(Settings.ACTION_WIFI_SETTINGS);
//                    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    mContext.startActivity(intent1);
                    try {
                        int sdkVersion = Utils.getAndroidSDKVersion();
                        if (sdkVersion == Build.VERSION_CODES.LOLLIPOP_MR1) {
                            Intent intent1 = new Intent();
                            ComponentName comp = new ComponentName("com.android.rockchip", "com.android.rockchip.RockExplorer");
                            intent1.setComponent(comp);
                            intent1.setAction("android.intent.action.VIEW");
                            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContext.startActivity(intent1);
                        } else if (sdkVersion == Build.VERSION_CODES.KITKAT) {
                            Intent intent1 = new Intent();
                            ComponentName comp = new ComponentName("com.softwinner.TvdFileManager", "com.softwinner.TvdFileManager.MainUI");
                            intent1.setComponent(comp);
                            intent1.setAction("android.intent.action.VIEW");
                            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContext.startActivity(intent1);
                        }
                        hidePopupWindow();
                    } catch (Exception e) {
                        Toast.makeText(x.app(), "没有安装文件浏览器，无法打开!", Toast.LENGTH_LONG).show();
                    }

                } else if (id == R.id.btn_four) {
//                    showToast("4");
//                    Intent home = new Intent(Intent.ACTION_MAIN);
//
//                    home.addCategory(Intent.CATEGORY_HOME);
//                    home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    mContext.startActivity(home);
                    Uri uri = Uri.parse("https://www.baidu.com");
                    Intent intent2 = new Intent(Intent.ACTION_VIEW, uri);
                    intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(intent2);
                    hidePopupWindow();
                } else if (id == R.id.btn_five) {
                    Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);

                    mHomeIntent.addCategory(Intent.CATEGORY_HOME);
                    mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                            | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                    mContext.startActivity(mHomeIntent);
                    hidePopupWindow();
//                    showToast("5");
                } else if (id == R.id.btn_six) {
//                    showToast("6");

                    DeviceUtils.rebootMachine();
                    DeviceUtils.reboot(x.app());
                } else if (id == R.id.btn_seven) {
//                    showToast("7");
//                        AppUpdate.devUpdateVersionInfo(mActivity);
                        hidePopupWindow();
                } else if (id == R.id.btn_eight) {
//                    showToast("8");
                    Intent intentBoot = new Intent();
                    intentBoot.setAction("com.etonedu.audoboot.receiver.updateVersion");
                    x.app().sendBroadcast(intentBoot);
                    hidePopupWindow();
                } else if (id == R.id.btn_nine) {
//                    showToast("9");
                    Intent unintent = new Intent();
                    unintent.setAction("com.etonedu.audoboot.receiver.uninstall");
                    x.app().sendBroadcast(unintent);
//                    Utils.setEthernetEnabled(x.app(),false);
//                    Utils.closeEthernet(x.app());
//                    hidePopupWindow();
                } else if (id == R.id.btn_zero) {
//                    showToast("0");
//                    Utils.setEthernetEnabled(x.app(),true);
//                    Utils.openEthernet(x.app());
                } else if (id == R.id.btn_go_back) {
//                    showToast("返回");
                    hidePopupWindow();
                }

//            hidePopupWindow();
        }
    }

    private static void showToast(Activity context,String msg) {
        Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
    }

    public static void showManageDialog(final Activity context) {
        final InternetDialog.Builder builder = new InternetDialog.Builder(context);
        String devId = Utils.getDevCode();
        builder.setTitle(devId);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String pwd = builder.getUrl();

                long currTime = System.currentTimeMillis();
                String currTimeStr = Utils.timestamp2String1(currTime,"MMdd");

                String data = "2015" + currTimeStr;

                int dt = Integer.valueOf(data);
                dt = dt * 2 - 2;

                String manage = dt + "";
                if (manage.equals(pwd)) {
//                    showPopupWindow(context);
                    WindowDialog windowDialog = new WindowDialog(context);
                    windowDialog.show();
                    dialog.dismiss();
                } else {
                    showToast(context,"密码不正确!");
                }
                Log.d("WindowUtil","url = " + pwd);

            }
        });

        builder.setBtnClose(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.setNegativeButton("刷新",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        SharedPreferencesUtil spu = SharedPreferencesUtil.getInstance(context);

                        EventBus.getDefault().post(MessageEnum.NONE);

                        dialog.dismiss();
                    }
                });

        builder.create().show();
    }

    private static void hideSoftInput(Activity context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }
}
